const { getList, getDetail, newBlog, updateBlog, delBlog } = require('../controller/blog');
const { SuccessModel, ErrorModel } = require('../model/resModel');

// 定义统一的登录验证 中间件
const loginCheck = req => {
  if (!req.session.username) {
    return new ErrorModel('还没登录');
  }
}

const handlerBlogRouter = async (req, res) => {
  const method = req.method;
  const id = req.query.id || req.postData.id;

  // 获取博客列表
  if (method === 'GET' && req.path === '/api/blog/list') {
    const author = req.query.author || '';
    const keyword = req.query.keyword || '';
    const listData = await getList(author, keyword);
    return new SuccessModel(listData);
  }

  // 获取博客详情
  if (method === 'GET' && req.path === '/api/blog/detail') {
    const detailData = await getDetail(id);
    return new SuccessModel(detailData[0]);
  }

  // 下面的都是需要登录才能做的路由 所有在匹配之前判断是否有登录
  const loginCheckResult = loginCheck(req);
  if (loginCheckResult) return loginCheckResult;

  // 新建一篇博客
  if (method === 'POST' && req.path === '/api/blog/new') {
    const blogData = req.postData;
    blogData.author = req.session.username;
    const data = await newBlog(blogData);
    return new SuccessModel(data.insertId);
  }

  // 更新博客
  if (method === 'POST' && req.path === '/api/blog/update') {
    const blogData = req.postData.blogData;
    const result = await updateBlog(id, blogData);
    if (result.affectedRows) { // 影响行数大于0说明更新成功
      return new SuccessModel('更新博客成功');
    } else {
      return new ErrorModel('更新博客失败');
    }
  }

  // 删除博客
  if (method === 'POST' && req.path === '/api/blog/del') {
    const author = req.session.username;
    const result = await delBlog(id, author);
    if (result.affectedRows) { // 影响行数大于0说明删除成功
      return new SuccessModel('删除博客成功');
    } else {
      return new ErrorModel('删除博客失败');
    }
  }
}

module.exports = handlerBlogRouter;
